import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api', // 默认API地址
  timeout: 15000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('access_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    const res = response.data;
    
    // 根据实际业务需求调整判断条件
    if (res.code === 200 || res.status === 'success') {
      return res;
    } else {
      console.error('响应错误:', res.message);
      return Promise.reject(new Error(res.message || 'Error'));
    }
  },
  (error) => {
    // 对响应错误做点什么
    console.error('响应错误:', error);
    return Promise.reject(error);
  }
);

// 封装请求方法
export const request = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, config);
  },

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config);
  },

  // 文件上传（multipart/form-data）
  upload<T = any>(url: string, data: FormData, config?: AxiosRequestConfig): Promise<T> {
    const headers = {
      ...(config?.headers || {}),
      'Content-Type': 'multipart/form-data',
    };
    return service.post(url, data, {
      ...config,
      headers,
    });
  },

  // 便捷文件上传：直接传 File
  uploadFile<T = any>(
    url: string,
    file: File,
    fieldName: string = 'file',
    config?: AxiosRequestConfig,
  ): Promise<T> {
    const formData = new FormData();
    formData.append(fieldName, file);
    return this.upload<T>(url, formData, config);
  },

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config);
  },

  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config);
  },
};

export default service;
